package com.nulldev.util.web.nTube.pages;

import java.net.SocketTimeoutException;
import java.util.Map;

import com.nulldev.util.languages.json.uniapi.UniJsonValue;
import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;
import com.nulldev.util.web.URLUtils.URLQueryParser;
import com.nulldev.util.web.nTubeExtensions.sponsorFree.SponsorBlockAPI;
import com.nulldev.util.web.nTubeExtensions.sponsorFree.SponsorBlockAPI.SponsorMeta;
import com.nulldev.util.web.nTubeExtensions.sponsorFree.SponsorBlockAPI.SponsorMeta.SponsorSegment;

public class GetSponsorsPage extends HttpPage3 {

	private final static Logger log = LoggerFactory.getLogger();

	public GetSponsorsPage() {
		super("/api/get_sponsors");
		super.setCachingMethod(CachingMethod.NO_CACHE);
		super.setUseJSONCaptchaPage(true);
		super.setChecks(EnhancedSecurityChecks.DISALLOW_POST_DATA, EnhancedSecurityChecks.ONLY_ALLOW_BASIC_METHODS);
	}

	private static final String JSON_MIME = "application/json; charset=utf-8";

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request _request) {
		final Map<String, String> request = URLQueryParser.extract(_request.url());
		if (!request.containsKey("v") || request.get("v").isEmpty()) {
			log.trace("videoID rejected, may be missing.");
			return new Response(400, createStream("{\"error\":\"Missing videoID argument!\"}")).setCustomMime(JSON_MIME);
		}
		final String videoID = request.get("v");
		try {
			final SponsorMeta sm = SponsorBlockAPI.auto(videoID);
			final UniJsonValue s = UniJsonValue.array();
			if (sm == null)
				return new Response(200, createStream(s.toString())).setCustomMime(JSON_MIME);
			final SponsorSegment[] ss = sm.segments();
			if (ss.length == 0)
				log.warn("sponsor_get: length == 0!");
			for (int i = 0; i < ss.length; i++) {
				final UniJsonValue uv = UniJsonValue.object(3);
				uv.add("start", ss[i].start);
				uv.add("end", ss[i].end);
				uv.add("uuid", ss[i].uuid);
				s.add(uv);
			}
			if (s.length() == 0)
				log.warn("sponsor_get: post_task_length == 0!");
			return new Response(200, s, s).setCustomMime(JSON_MIME);
		} catch (SocketTimeoutException e) {
			log.error("Failed to get sponsor data! [at=json,by=SocketTimeoutException]");
			return new Response(503);
		} catch (Exception e) {
			log.error(e);
			return new Response(503);
		}
	}

}
